<template>
  <div>
    <el-card>
      <span>待签收订单</span>
      <el-divider></el-divider>

      <el-row>
        <el-col :span="12">
          <el-button @click="getNeedReceiveOrder"> 刷新 </el-button>
        </el-col>
        <el-col :span="12" align="right">
          <!-- 序列号入库 -->
          <el-button @click="openUi" type="primary">批量签收</el-button>
        </el-col>
      </el-row>

      <!-- 更具所有未入库的寄回设备的序列号查询订单，查询的订单状态有（已发货，已寄回，已逾期，坏账） -->
      <!-- 如果没有查询到则返回签收序列号，和运单号 -->
      <!-- 判断寄回信息，是否缺配件，损坏，如果有则将添加到日志中，再更新订单签收单号，将状态更新为已签收-->
      <!-- 如果没有更新订单签收单号，更新订单状态为已签收 -->
      <el-table
        :data="receiveOrderList"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50"> </el-table-column>
        <el-table-column type="index" width="50"> </el-table-column>
        <el-table-column label="订单信息" width="360">
          <template slot-scope="scope">
            <div>
              平台：<strong>{{ scope.row.orderPlatform }}</strong>
            </div>
            <div>
              订单编号：<strong>{{ scope.row.orderNumber }}</strong>
            </div>
            <div>
              型号：<strong>{{ scope.row.tradeName }}</strong>
            </div>
            <div>
              商品信息：<strong>{{ scope.row.setMeal }}</strong>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="客户信息" width="260">
          <template slot-scope="scope">
            <div>
              姓名：<strong>{{ scope.row.userName }}</strong>
            </div>
            <div>
              电话：<strong>{{ scope.row.phone }}</strong>
            </div>
            <div>
              寄回单号:
              <strong>{{ scope.row.receiveGoodsDto.oddNumber }}</strong>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="寄出设备" wdith="80">
          <template slot-scope="scope">
            <div
              v-for="(sendOutSerialNunmber, index) in scope.row.serialNumbers"
              :key="index"
              style="margin: 10px"
            >
              <el-tag effect="dark"
                ><strong>{{
                  sendOutSerialNunmber.serialNumber
                }}</strong></el-tag
              >
            </div>
          </template>
        </el-table-column>

        <el-table-column label="寄回设备" wdith="80">
          <template slot-scope="scope">
            <div
              v-for="(getSerialNunmber, index) in scope.row.receiveGoodsDto
                .goodsSerialNumbers"
              :key="index"
              style="margin: 10px"
            >
              <el-tag effect="dark"
                ><strong
                  >{{ getSerialNunmber.serialNumber }} -{{
                    getSerialNunmber.status ? "已入库" : "待入库"
                  }}</strong
                ></el-tag
              >
            </div>
          </template>
        </el-table-column>

        <el-table-column label="收货信息" wdith="160">
          <template slot-scope="scope">
            <div>设备状态：{{ scope.row.receiveGoodsDto.info }}</div>
            <div>备注：{{ scope.row.receiveGoodsDto.remark }}</div>
          </template>
        </el-table-column>
        <el-table-column label="订单日志">
          <template slot-scope="scope">
            <!-- 显示两天最新的日志 -->
            <div v-if="scope.row.orderLogs.length > 0">
              <el-popover
                placement="left"
                title="订单日志"
                width="520"
                trigger="hover"
              >
                <el-timeline :reverse="false">
                  <el-timeline-item
                    v-for="(logs, index) in scope.row.orderLogs"
                    :key="index"
                    :timestamp="logs.createTime"
                    :color="logs.type == false ? '#909399' : '#409EFF'"
                  >
                    <span>{{ logs.operator }}</span>
                    <span
                      v-if="
                        logs.log === '补发订单' ||
                        logs.log === '重复订单' ||
                        logs.log === '转寄订单'
                      "
                      style="color: #f56c6c"
                    >
                      {{ logs.log }}</span
                    >
                    <span v-else> {{ logs.log }}</span>
                  </el-timeline-item>
                </el-timeline>

                <el-badge
                  v-if="getSpecialOrderNum(scope.row.orderLogs) > 0"
                  :value="getSpecialOrderNum(scope.row.orderLogs)"
                  class="item"
                  slot="reference"
                  style="margin-top: 10px"
                >
                  <el-button type="text">
                    <strong>{{ scope.row.orderLogs[0].log }}</strong>
                  </el-button>
                </el-badge>
                <el-button type="text" slot="reference" v-else>
                  <strong>{{ scope.row.orderLogs[0].log }}</strong>
                </el-button>
              </el-popover>
              <!-- 添加日志时间 -->
              <div>
                <span style="margin-right: 6px">{{
                  scope.row.orderLogs[0].operator
                }}</span
                ><span>{{ scope.row.orderLogs[0].createTime }}</span>
              </div>
            </div>

            <el-button type="text" @click="openAddlogUi(scope.row)"
              >添加日志</el-button
            >
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="receiveOrder(scope.row)"
              >确认签收</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 自定义日志 -->
    <el-dialog
      title="自定义日志"
      :visible.sync="dialogVisibleLog"
      width="520px"
      :before-close="handleClose"
      @close="clearLogForm"
    >
      <el-form label-width="80px" :model="userLogForm">
        <el-form-item label="订单类型">
          <el-checkbox-group v-model="userLogForm.types">
            <el-checkbox label="补发订单" name="type"></el-checkbox>
            <el-checkbox label="重复订单" name="type"></el-checkbox>
            <el-checkbox label="转寄订单" name="type"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="输入日志">
          <el-input
            type="textarea"
            :rows="4"
            v-model="userLogForm.log"
            width="400"
            maxlength="255"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleLog = false">取 消</el-button>
        <el-button type="primary" @click="addUserLog">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 批量签收订单 -->
    <el-dialog
      title="序列号入库"
      :visible.sync="dialogVisibleSerivalNumber"
      width="50%"
      :before-close="handleClose"
      @close="clearForm"
    >
      <div align="center">
        <el-row>
          <el-col :span="12"
            >出库仓库：<el-select
              v-model="inSerialNumberForm.outWarehouseId"
              clearable
              placeholder="出库仓库"
              @change="getInWarehouseNum"
            >
              <el-option
                v-for="item in allwareHouseName"
                :key="item.id"
                :label="item.warehouseName"
                :value="item.id"
              >
              </el-option> </el-select
          ></el-col>
          <el-col :span="12">
            入库仓库：<el-select
              v-model="inSerialNumberForm.inWarehouseId"
              clearable
              placeholder="入库仓库"
            >
              <el-option
                v-for="item in allwareHouseName"
                :key="item.id"
                :label="item.warehouseName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-col>
        </el-row>
      </div>
      <el-row style="margin-top: 10px">
        <el-tabs
          type="border-card"
          v-model="activeName"
          v-loading="transferLoading"
        >
          <el-tab-pane :label="getTableName('在库')" name="first">
            <el-table :data="inSerialNumberForm.inWarehouseSerialNumber">
              <el-table-column prop="serialNumber" label="序列号">
              </el-table-column>
              <el-table-column
                prop="productName"
                label="商品名称"
              ></el-table-column>
              <el-table-column
                prop="warehouseName"
                label="所在仓库"
              ></el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane :label="getTableName('不在库')" name="second">
            <el-table :data="inSerialNumberForm.outWarehouseSerialNumber">
              <el-table-column
                prop="serialNumber"
                label="序列号"
              ></el-table-column>
              <el-table-column
                prop="productName"
                label="商品名称"
              ></el-table-column>
              <el-table-column
                prop="warehouseName"
                label="所在仓库"
              ></el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleSerivalNumber = false">取 消</el-button>
        <el-button type="primary" @click="reOrders">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import orderApi from "@/api/order";
import orderLogApi from "@/api/orderLog";
import warehouseApi from "@/api/inventory/warehouse";
import inventoryApi from "@/api/inventory/inventory";

export default {
  data() {
    return {
      receiveOrderList: [],

      loading: false,

      // 日志
      dialogVisibleLog: false,

      dialogVisibleSerivalNumber: false,

      transferLoading: false,

      userLogForm: {
        types: [],
      },

      multipleSelection: [],

      // 查询序列号状态数据
      transferData: {
        serialNumbers: [],
      },

      // 仓库名称
      allwareHouseName: [],
      // 序列号入库表单
      inSerialNumberForm: {
        outWarehouseId: "",
        inWarehouseId: "",
        serialNumbers: [],
        inWarehouseSerialNumber: [],
        outWarehouseSerialNumber: [],
      },

      activeName: "first",
    };
  },
  methods: {
    // 确认关闭对话框
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    clearForm() {
      this.inSerialNumberForm = {
        outWarehouseId: "",
        inWarehouseId: "",
        serialNumbers: [],
        inWarehouseSerialNumber: [],
        outWarehouseSerialNumber: [],
      };

      this.transferData = {
        serialNumbers: [],
      };
    },

    // 清空自定义日志对话框
    clearLogForm() {
      // 自定义日志
      // 清空表单数据
      this.userLogForm = {
        types: [],
      };
    },

    // 获取需要签收的订单

    getNeedReceiveOrder() {
      this.loading = true;
      orderApi.getSendBackOrder().then((response) => {
        this.receiveOrderList = response.data;

        this.loading = false;
      });
    },

    // 获取订单特殊订单个数
    getSpecialOrderNum(logs) {
      var num = 0;

      logs.forEach((item) => {
        if (
          item.log === "补发订单" ||
          item.log === "重复订单" ||
          item.log === "转寄订单"
        ) {
          num += 1;
        }
      });

      return num;
    },

    // 获取收货信息
    getAddressInfo(row) {
      var username = row.userName;
      var phone = row.phone;
      var address = row.address;

      return username + "," + phone + "," + address;
    },

    // 修改订单信息
    // 更新订单备注
    updateOrderRemark(order) {
      var model = "remarkInfo";
      var pushOrder = {
        id: order.id,
        orderNumber: order.orderNumber,
        remark: order.remark,
        orderStatus: order.orderStatus,
        stockStatus: order.stockStatus,
        debitStatus: order.debitStatus,
        addressStatus: order.addressStatus,
        startTime: order.startTime,
        ageing: order.ageing,
      };
      // 提交数据给后台
      orderApi.saveOrder(pushOrder, model).then((response) => {
        this.$message({
          showClose: true,
          message: response.message,
          type: "success",
        });
        // 刷新表单
        this.getNeedReceiveOrder();
      });
    },

    addUserLog() {
      if (
        this.userLogForm.types.length == 0 &&
        (this.userLogForm.log == undefined || this.userLogForm.log == null)
      ) {
        this.$message({
          type: "error",
          message: "日志不能为空",
        });
      } else {
        orderLogApi.addLog(this.userLogForm).then((response) => {
          if (response.code == 20000) {
            this.$message({
              type: "success",
              message: response.message,
            });
            // 清空表单数据
            this.userLogForm = {
              types: [],
            };
            this.dialogVisibleLog = false;
            this.getNeedReceiveOrder();
          } else {
            this.$message({
              type: "error",
              message: response.message,
            });
          }
        });
      }
    },
    // 添加自定义日志
    openAddlogUi(row) {
      this.userLogForm.id = row.id;
      this.dialogVisibleLog = true;
    },

    // 确认签收订单
    receiveOrder(row) {
      this.$confirm("确定要签收该订单：" + row.orderNumber, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        var sendData = {
          orderId: row.id,
          receiveGoodsId: row.receiveGoodsDto.id,
        };

        orderApi.receiveOrder(sendData).then((response) => {
          this.$message({
            type: "success",
            message: response.message,
          });

          this.getNeedReceiveOrder();
        });
      });
    },

    handleSelectionChange(val) {
      // 保存选中的对象
      this.multipleSelection = val;
    },

    // 批量签收UI
    openUi() {
      this.dialogVisibleSerivalNumber = true;

      // 获取仓库
      this.getAllwareHouseName();

      // 获取选中序列号
      this.multipleSelection.forEach((item) => {
        item.receiveGoodsDto.goodsSerialNumbers.forEach((s) => {
          this.inSerialNumberForm.serialNumbers.push(s.serialNumber);
        });
      });
    },

    // 批量签收订单
    reOrders() {
      if (
        this.inSerialNumberForm.inWarehouseId == null ||
        this.inSerialNumberForm.inWarehouseId == undefined ||
        this.inSerialNumberForm.inWarehouseId === ""
      ) {
        this.$message.error("请选择入库仓库");
        return;
      }
      if (
        this.inSerialNumberForm.outWarehouseId == null ||
        this.inSerialNumberForm.outWarehouseId == undefined ||
        this.inSerialNumberForm.outWarehouseId === ""
      ) {
        this.$message.error("请选择出库仓库");
        return;
      }
      if (
        this.inSerialNumberForm.inWarehouseId ===
        this.inSerialNumberForm.outWarehouseId
      ) {
        this.$message.error("出库仓库不能和入库仓库相同");
        return;
      }
      if (
        this.inSerialNumberForm.inWarehouseSerialNumber == null ||
        this.inSerialNumberForm.inWarehouseSerialNumber == undefined ||
        this.inSerialNumberForm.inWarehouseSerialNumber.length < 1
      ) {
        this.$message.error("入库序列号列表为空，入库失败。");
        return;
      }
      this.$confirm(
        "你确定要批量签收这些序列号吗，这个此操作生成调拨单号，调拨库存中的设备",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        // 发送给后端的数据模版
        var sendData = {
          orderIds: [], // {orderId, 收货Id}
          serialNumbers: [],
          outWarehouseId: "",
          inWarehouseId: "",
        };

        // 入库序列号

        sendData.outWarehouseId = this.inSerialNumberForm.outWarehouseId;
        sendData.inWarehouseId = this.inSerialNumberForm.inWarehouseId;

        // 获取需要签收的订单编号
        console.log(this.multipleSelection);
        this.multipleSelection.forEach((item) => {
          for (const s of item.receiveGoodsDto.goodsSerialNumbers) {
            for (const inserialnumber of this.inSerialNumberForm
              .inWarehouseSerialNumber) {
              if (s.serialNumber == inserialnumber.serialNumber) {
                let data = {
                  orderId: item.id,
                  receiveId: item.receiveGoodsDto.id,
                };
                sendData.orderIds.push(data);
                sendData.serialNumbers.push(inserialnumber.serialNumber);
                break;
              }
            }
          }
        });
        orderApi.receiveOrders(sendData).then((response) => {
          if (response.code === 20000) {
            this.$message({
              type: "success",
              message: response.message,
            });
            // 刷新
            this.getNeedReceiveOrder();

            // 关闭对话框
            this.dialogVisibleSerivalNumber = false;
          } else {
            this.$message({
              type: "error",
              message: response.message,
            });
          }
        });
      });
    },

    // 获取序列号在库情况
    getInWarehouseNum() {
      // 获取序列号状态
      // 返回的数据在库，和不在库两组数据{Inwarehouse:[传递的序列号], outWarehouse:[传递的序列号]}
      this.transferLoading = true;
      this.transferData.warehouseId = this.inSerialNumberForm.outWarehouseId;
      this.transferData.serialNumbers = this.inSerialNumberForm.serialNumbers;

      this.transferData.type = false;
      inventoryApi
        .getInWarehouseSerialNumber(this.transferData)
        .then((response) => {
          if (response.code == 20000) {
            this.inSerialNumberForm.inWarehouseSerialNumber =
              response.data.inWarehouseSerialNumber;
            this.inSerialNumberForm.outWarehouseSerialNumber =
              response.data.outWarehouseSerialNumber;
          } else {
            this.$message({ type: "error", message: response.message });
          }

          this.transferLoading = false;
        });
    },

    // 获取所有仓库名称
    getAllwareHouseName() {
      warehouseApi.selseAllName().then((response) => {
        this.allwareHouseName = response.data;
      });
    },

    getTableName(name) {
      if (name === "在库") {
        return (
          name +
          "(" +
          this.inSerialNumberForm.inWarehouseSerialNumber.length +
          ")"
        );
      } else if (name === "不在库") {
        return (
          name +
          "(" +
          this.inSerialNumberForm.outWarehouseSerialNumber.length +
          ")"
        );
      }
    },
  },

  created() {
    this.getNeedReceiveOrder();
  },
};
</script>

<style scoped></style>
